package devcamp.teama.yahooooooo.api;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import devcamp.teama.yahooooooo.dao.YahoooooooDao;
import devcamp.teama.yahooooooo.dto.RegistrationDto;
import devcamp.teama.yahooooooo.json.RegistrationJson;
import devcamp.teama.yahooooooo.util.ParameterUtils;
import devcamp.teama.yahooooooo.util.YahoooooooUtils;

@SuppressWarnings("serial")
public class RegistrationServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        registration(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        registration(req, resp);
    }

    void registration(HttpServletRequest req, HttpServletResponse resp) {

        RegistrationJson json = new RegistrationJson();
        // パラメータからデータ取得して
        String userName = req.getParameter(ParameterUtils.USER_NAME);
        String twitterId = req.getParameter(ParameterUtils.TWITTER_ID);
        if (!validate(userName, twitterId)) {
            json.registration = false;
            printJson(resp, YahoooooooUtils.Object2Json(json));
            return;
        }
        // データ保存
        RegistrationDto dto = registaration(userName, twitterId);

        // jsonデータ作成
        json.id = dto.getId();
        json.registration = true;

        // 戻り値をjsonで出力
        printJson(resp, YahoooooooUtils.Object2Json(json));
    }

    boolean validate(String userName, String twitterId) {
        if (userName == null || twitterId == null) {
            return false;
        }
        if (userName.equals("") || twitterId.equals("")) {
            return false;
        }
        return true;
    }

    RegistrationDto registaration(String userName, String twitterId) {
        RegistrationDto dto = new RegistrationDto();
        dto.setUserName(userName);
        dto.setTwitterId(twitterId);
        dto.setRegistration(true);
        YahoooooooDao dao = new YahoooooooDao();
        dao.insert(dto);
        return dto;
    }

    void printJson(HttpServletResponse resp, String outputJson) {
        resp.setContentType("text/plain");
        try {
            resp.getWriter().print(outputJson);
        } catch (IOException e) {
            e.printStackTrace();
            // FIXME:ログの出力
        }
    }

}
